package com.example.it.review.acvitity.customview;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

import com.example.it.review.R;

/**
 * Created by 鲁迅认识的那只猹 on 9/27/2017 2:33 PM.
 * Emial 1258730808@qq.com
 * Desc:
 */

public class EditTextWithDelete extends EditText implements TextWatcher {

    private Drawable drawableDel;

    public EditTextWithDelete(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public EditTextWithDelete(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public EditTextWithDelete(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    public EditTextWithDelete(Context context) {
        super(context);
        init();
    }

    //初始化
    void init() {
        this.addTextChangedListener(this);
        drawableDel = getResources().getDrawable(R.drawable.close);
        setDrawable();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence var1, int var2, int var3, int var4) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        setDrawable();
    }

    void setDrawable() {
        if (this.length() > 0) {
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableDel, null);
        } else {
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    }

    /**
     * 设置删除按钮的点击事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.drawableDel == null) return false;

        if (event.getAction() == MotionEvent.ACTION_UP)
            //计算方式为 当前点中的x 大于 除了close 图片的x点 那么就证明点中了close图片
            if (event.getX() > this.getWidth() - drawableDel.getIntrinsicWidth()) {
                setText("");
            }
        return super.onTouchEvent(event);
    }
}
